<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      placeholder="请输入搜索关键词"
      show-action
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 推荐词 -->
    <van-cell-group>
      <van-cell
        v-for="(item, index) in showList"
        :key="index"
        icon="search"
        @click="
          $router.push({
            path: '/articleSearch',
            query: { q: list[index] }
          })
        "
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 搜索历史 -->
    <van-cell-group>
      <van-cell title="历史记录"> </van-cell>
      <van-cell title="单元格">
        <van-icon name="close" />
      </van-cell>
      <van-cell title="单元格">
        <van-icon name="close" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from './home'
export default {
  name: 'search',
  data () {
    return {
      value: '',
      list: [],
      tiemId: null
    }
  },
  methods: {
    onSearch () {
      //console.log(this.value)
      //跳转搜索页
      this.$router.push({
        path: '/articleSearch',
        query: {
          // url的参数, 类似get请求的传参
          q: this.value
        }
      })
    },
    onInput () {
      //开启函数防抖优化性能
      //(1)每一次触发事件，先清除上一次定时器。以本次为准
      clearTimeout(this.tiemId)
      //(2)开启防抖定时器 间隔0.5s执行（防抖间隔）
      this.tiemId = setTimeout(async () => {
        //非空判断
        if (this.value.length == 0) {
          this.list = [] //完成清空列表
          return
        }
        //console.log(this.value)
        let res = await getSuggestion(this.value)
        console.log(res)
        // 绑定数据
        this.list = res.data.data.options
      }, 500)
    }
  },
  //计算属性
  computed: {
    showList () {
      return this.list.map(item => {
        let regexp = new RegExp(this.value, 'ig')

        return item.replace(
          regexp,
          match => `<span style="color:red">${match}</span>`
        )
      })
    }
  }
}
</script>

<style></style>
